﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BudgetManager.ViewModels;
using BudgetManager.Data;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;
using BudgetManager.Entities;
using BudgetManager.Resources;
using BudgetManager.Utils;

namespace BudgetManager
{
    public partial class ExpenseReports : PhoneApplicationPage
    {
        private BudgetMgrDAL budgetManager = new BudgetMgrDAL();
        public ExpenseReports()
        {
            InitializeComponent();
            this.Loaded += ExpenseReports_Loaded;
        }

        void ExpenseReports_Loaded(object sender, RoutedEventArgs e)
        {
            var viewModel = new ExpenseReportViewModel();
            DataContext = viewModel;
            setDataForOverviewPage();
        }

        private void setDataForOverviewPage()
        {
            var totalExpense = 0.0;
            List<ExpensesOverview> expEntity = new List<ExpensesOverview>();
            List<DatedExpenses> datedExp = new List<DatedExpenses>();
            if (IsolatedStorageSettings.ApplicationSettings.Contains("ToggleBalance") && IsolatedStorageSettings.ApplicationSettings.Contains("BalanceLimit"))
            {
                var startDate = DateTime.Parse(IsolatedStorageSettings.ApplicationSettings["LimitSetDate"].ToString());
                totalExpense = budgetManager.GetTotalExpense(startDate, startDate.AddDays(30));
                var exp = budgetManager.GetDetailedExpenses(startDate, startDate.AddDays(30));
                expEntity = getDataForPieChart(exp);
                datedExp = getDateForColumnChart(exp);
                var configuredBalance = float.Parse(IsolatedStorageSettings.ApplicationSettings["BalanceLimit"].ToString());
                if (totalExpense <= configuredBalance)
                {
                    //within limit
                    balanceConfiguredWithinLimit.Visibility = System.Windows.Visibility.Visible;
                    balanceProgess.Maximum = configuredBalance;
                    balanceProgess.Value = totalExpense;
                    txtRemaining.Text = string.Format("{0} / {1}", totalExpense, configuredBalance);
                }
                else
                {
                    //exceeds limit
                    balanceConfiguredExceedsLimit.Visibility = System.Windows.Visibility.Visible;
                    txtExceeded.Text = string.Format("{0} / {1}", totalExpense, configuredBalance);
                }
            }
            else
            {
                totalExpense = budgetManager.GetTotalExpense();
                if (totalExpense > 0)
                {
                    var exp = budgetManager.GetDetailedExpenses();
                    expEntity = getDataForPieChart(exp);
                    datedExp = getDateForColumnChart(exp);
                    //Balance not configured. just show the total expense calculated from first date.
                    balanceNotConfigured.Visibility = System.Windows.Visibility.Visible;
                    txtTotalExpense.Text = string.Format(AppResources.ConfiguredBalanceText + " : " + totalExpense.ToString());
                    txtDate.Text = string.Format(AppResources.ExpenseCalculatedFromDateText, DateTime.Now.ToShortDateString());
                }
                else
                {
                    panelwithData.Visibility = System.Windows.Visibility.Collapsed;
                    panelWithoutData.Visibility = System.Windows.Visibility.Visible;
                }
            }
            pieOverviewChart.DataSource = expEntity;
            datedExpenseChart.DataSource = datedExp;
        }

        private List<DatedExpenses> getDateForColumnChart(List<Expense> expensesList)
        {
            ObservableCollection<DatedExpenses> exp = new ObservableCollection<DatedExpenses>();
            var expGrp = from expense in expensesList
                         group expense by expense.ExpenseDate into grp
                         select new DatedExpenses() { Title = ((DateTime)grp.Key).ToString("MMM") + "\n" + ((DateTime)grp.Key).Day, Value = grp.Sum(c => c.ExpenseAmount) };

            return expGrp.ToList();
        }

        private List<ExpensesOverview> getDataForPieChart(List<Expense> expensesList)
        {
            ObservableCollection<ExpensesOverview> exp = new ObservableCollection<ExpensesOverview>();
            var expGrp = from expense in expensesList
                         group expense by expense.Category into grp
                         select new ExpensesOverview() { Title = grp.Key, Value = grp.Sum(c => c.ExpenseAmount) };

            return expGrp.ToList();
        }

        private void onItemLongPressed(object sender, System.Windows.Input.GestureEventArgs e)
        {
            StackPanel s = sender as StackPanel;
            StackPanel datePart = s.Children[0] as StackPanel;
            StackPanel detailpart = s.Children[1] as StackPanel;
            ExpenseReport exp = new ExpenseReport() { Category = (detailpart.Children[2] as TextBlock).Text, Comments = (detailpart.Children[1] as TextBlock).Text, ExpenseAmount = float.Parse((detailpart.Children[0] as TextBlock).Text), Date = Int16.Parse((datePart.Children[0] as TextBlock).Text), Month = (datePart.Children[1] as TextBlock).Text, Year = Int16.Parse((datePart.Children[2] as TextBlock).Text) };
            NavigationService.Navigate(new Uri(String.Format("/AddExpense.xaml?expDetail={0}", exp), UriKind.Relative));
        }

        private void onDeleteExpense(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var mBoxResult = MessageBox.Show(AppResources.ExpenseDeleteMessageText, AppResources.WarningMessageText, MessageBoxButton.OKCancel);
            switch (mBoxResult)
            {
                case MessageBoxResult.OK:
                    ExpenseReport element = (sender as MenuItem).DataContext as ExpenseReport;
                    bool status = budgetManager.DeleteExpense(element.ExpenseId);
                    NavigationService.Navigate(new Uri(String.Format("/ExpenseReports.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
                    break;
                case MessageBoxResult.Cancel:
                default:
                    break;
            }
        }

        private void onEditExpense(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ExpenseReport element = (sender as MenuItem).DataContext as ExpenseReport; 
            AppSettingsHelper.saveAppSettings("EditElement", element);
            NavigationService.Navigate(new Uri(String.Format("/AddExpense.xaml?expDetail={0}", "1"), UriKind.Relative));
        }

        #region OVERRIDED_METHODS
        /// <summary>
        /// OnNavigated event
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string id = string.Empty;
            if (NavigationContext.QueryString.TryGetValue("id", out id))
            {
                if (NavigationService.CanGoBack)
                    NavigationService.RemoveBackEntry();
            }
        }
        #endregion
    }
}